package com.easy.controller;

import com.easy.service.AppointmentService;
import com.easy.util.Result;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("appointment")
public class AppointmentController {

    @Resource
    private AppointmentService appointmentService;

    /**
     * 从请求头获取用户ID
     */
    private Integer resolveUserId(Map<String,Object> body, Integer headerUserId) {
        if (headerUserId != null) return headerUserId;
        Object uid = body == null ? null : body.get("user_id");
        if (uid instanceof Number) return ((Number) uid).intValue();
        return 1;
    }

    @PostMapping("reserve")
    public Result reserve(@RequestBody Map<String,Object> payload,
                          @RequestHeader(value = "X-User-Id", required = false) Integer userIdHeader) {
        Integer scheduleId = payload.get("schedule_id") == null ? null : Integer.parseInt(payload.get("schedule_id").toString());
        Integer doctorId   = payload.get("doctor_id")   == null ? null : Integer.parseInt(payload.get("doctor_id").toString());
        Integer userId     = resolveUserId(payload, userIdHeader);

        appointmentService.reserve(userId, doctorId, scheduleId);
        return Result.success("预约成功");
    }

    @GetMapping("my")
    public Result my(@RequestHeader(value = "X-User-Id", required = false) Integer userIdHeader) {
        Integer userId = userIdHeader == null ? 1 : userIdHeader;
        return Result.success(appointmentService.myList(userId));
    }

    @DeleteMapping("cancel/{id}")
    public Result cancel(@PathVariable("id") Integer id,
                         @RequestHeader(value = "X-User-Id", required = false) Integer userIdHeader) {
        Integer userId = userIdHeader == null ? 1 : userIdHeader;
        appointmentService.cancel(id, userId);
        return Result.success("取消成功");
    }
}
